import {
  createWebHashHistory,
  createWebHistory,
  createRouter,
} from 'vue-router'

import NProgress from 'nprogress'
import 'nprogress/nprogress.css'

// 静态加载（里面代码会默认执行）
// import HomeView from '../page/HomeView.vue'
// import ListView from '../page/ListView.vue'
// import DetailView from '../page/DetailView.vue'
// import ArticleView from '../page/ArticleView.vue'
// import Basketball from '../page/Basketball.vue'
// import NbaBasketball from '../page/NbaBasketball.vue'
// import CbaBasketball from '../page/CbaBasketball.vue'

// 动态加载（只有访问对应的路由，其组件才会执行）
const HomeView = () => import('../page/HomeView.vue')
const ListView = () => import('../page/ListView.vue')
const DetailView = () => import('../page/DetailView.vue')
const ArticleView = () => import('../page/ArticleView.vue')
const Basketball = () => import('../page/Basketball.vue')
const NbaBasketball = () => import('../page/NbaBasketball.vue')
const CbaBasketball = () => import('../page/CbaBasketball.vue')

const routes = [
  // 路由重定向
  { path: '/', redirect: '/home' },
  { path: '/home', component: HomeView, meta: { title: '首页' } },
  { path: '/list', component: ListView, meta: { title: '列表页' } },
  {
    path: '/basketball',
    component: Basketball,
    redirect: '/basketball/nba',
    meta: { title: '篮球' },
    children: [
      {
        // /basketball/nba
        path: 'nba',
        component: NbaBasketball,
        name: 'mynba',
        meta: { title: 'nba' },
      },
      {
        path: 'cba',
        component: CbaBasketball,
        meta: { title: 'cba' },
      },
    ],
  },
  { path: '/detail', component: DetailView },
  // 路由参数
  { path: '/article/:id', component: ArticleView },
]

const router = createRouter({
  // 路由模式 hash :打包=》dist=》无需要服务器配置
  // history: createWebHashHistory(),
  // 路由模式 历史模式： 1.打包=》dist=>需要服务器额外配置 2. seo较好
  history: createWebHistory(),
  // 路由配置项
  routes,
  scrollBehavior(to, from, savedPosition) {
    if (savedPosition) {
      return savedPosition
    } else {
      return { top: 0 }
    }
  },
})

NProgress.configure({ showSpinner: false })
// 全局前守卫
router.beforeEach((to, from) => {
  // 作用：1. 验证权限！！！！！ 2.网页跳转进度条 。。。
  NProgress.start()
  document.title = to.meta.title
  console.log('前守卫')
})
// 全局后守卫
router.afterEach((to, from) => {
  NProgress.done()
  console.log('后守卫')
})

export default router
